package com.zhiwei.msf.gateway.hystrix;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.netflix.hystrix.exception.HystrixTimeoutException;
import com.zhiwei.msf.common.constant.ResultResponseMsg;

import lombok.extern.slf4j.Slf4j;

/**
 * Hystrix服务熔断
 */
@Component
@Slf4j
public class HystrixFallbackProvider implements FallbackProvider {

    /**
     * 熔断服务名称
     *
     * @return
     */
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        log.error("hystrix服务【{}】熔断", route, cause);
        if (cause instanceof HystrixTimeoutException) {
            return response(504, route);
        } else {
            return response(500, route);
        }
    }

    /**
     * 自定义熔断响应
     *
     * @param status
     * @return
     */
    private ClientHttpResponse response(final int status, String route) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() {
                return 200;
            }

            @Override
            public String getStatusText() {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() {
                String responseBody;
                if (status == 504) {
                    responseBody = ResultResponseMsg.buildFailureResultMsg("当前服务【" + route + "】未注册，请稍后再重试").toString();
                } else {
                    responseBody = ResultResponseMsg.buildFailureResultMsg("当前服务【" + route + "】未启动，请启动再重试").toString();
                }
                return new ByteArrayInputStream(responseBody.getBytes(Charset.defaultCharset()));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}